from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from LogisticsCard.models import UserPriceConfig, Customer, Package

@login_required
def price_config_edit_view(request, customer_id, config_id):
    customer = get_object_or_404(Customer, id=customer_id)
    config = get_object_or_404(UserPriceConfig, id=config_id, customer=customer, delete_at__isnull=True)
    packages = Package.objects.filter(delete_at__isnull=True)
    error_msg = ''
    if request.method == 'POST':
        package_name = request.POST.get('package')
        price = request.POST.get('price')
        # 唯一性校验：同客户同资费包只能有一个配置（排除自身）
        exists = UserPriceConfig.objects.filter(customer=customer, package=package_name, delete_at__isnull=True).exclude(id=config.id).exists()
        if exists:
            error_msg = f'该客户的资费包“{package_name}”已存在单价配置！'
        else:
            if (not price or price == ''):
                package_obj = packages.filter(name=package_name).first()
                if package_obj:
                    price = package_obj.price
            config.package = package_name
            config.price = price
            config.save()
            return redirect('price_config_list', customer_id=customer.id)
    return render(request, 'customer/price_config_edit.html', {'customer': customer, 'config': config, 'packages': packages, 'error_msg': error_msg})

@login_required
def price_config_delete_view(request, customer_id, config_id):
    from django.utils import timezone
    customer = get_object_or_404(Customer, id=customer_id)
    config = get_object_or_404(UserPriceConfig, id=config_id, customer=customer, delete_at__isnull=True)
    config.delete_at = timezone.now()
    config.save()
    return redirect('price_config_list', customer_id=customer.id)
